/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.mapper.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * 试题选项转换
 *
 * @author SAGITTAR
 * @since 2017
 */
@MappedTypes(value = { List.class })
@MappedJdbcTypes(value = { JdbcType.VARCHAR })
public class ChoiceTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return trimBracketsAndToList(rs.getString(columnName));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return trimBracketsAndToList(rs.getString(columnIndex));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return trimBracketsAndToList(cs.getString(columnIndex));
    }

    /**
     * 将原始选项转为列表形式
     *
     * @param source 原始选项
     * @return 将原始选项转为列表形式
     */
    private List<String> trimBracketsAndToList(String source) {
        String choice = StringUtils.substringBetween(source, "[", "]").trim();
        return Arrays.stream(choice.split(",")).map(String::trim).collect(Collectors.toList());
    }
}
